package com.benhil.hrms.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.stereotype.Component;

import com.benhil.hrms.model.PersistentObject;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
public class JsonModelConverter {

	public <T extends PersistentObject> Collection<T> getModelsFromRequest(Object data, Class<T> clazz) {
		Collection<T> list;
		// it is an array - have to cast to array object
		if (data.toString().indexOf('[') > -1) {
			list = getListModelsFromJSON(data, clazz);
		// it is only one object - cast to object/bean
		} else { 
			T model = getModelFromJSON(data, clazz);
			list = new ArrayList<T>();
			list.add(model);
		}

		return list;
	}

	
	@SuppressWarnings("unchecked")
	private <T extends PersistentObject> T getModelFromJSON(Object data, Class<T> clazz) {
		JSONObject jsonObject = JSONObject.fromObject(data);
		T model = (T) JSONObject.toBean(jsonObject, clazz);
		return model;
	}
	
	@SuppressWarnings("unchecked")
	private <T extends PersistentObject> Collection<T> getListModelsFromJSON(Object data, Class<T> clazz) {
		JSONArray jsonArray = JSONArray.fromObject(data);
		Collection<T> models = (Collection<T>) JSONArray.toCollection(jsonArray, clazz);
		return models;
	}

	@SuppressWarnings("unchecked")
	public List<Long> getListModelIdFromJSON(Object data) {
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<Long> idModels = (List<Long>) JSONArray.toCollection(jsonArray, Long.class);
		return idModels;
	}
}
